<template>
  <div class="app-container">
    <div class="body-div">
      <el-button type="primary" style="float: right" @click="back()"
        >返回详情页面</el-button
      >
      <el-tabs v-model="activeName" @tab-click="tabClick" type="card">
        <el-tab-pane
          v-for="(tab, index) in tabData"
          :key="index"
          :label="tab.conditionType"
          :name="tab.conditionName"
        >
        </el-tab-pane>
      </el-tabs>
      <div style="padding: 10px">
        <div style="display: flex; margin-bottom: 10px">
          <div class="shuxian"></div>
          <span class="headtitle">设计方案计算</span>
        </div>
        <div class="border-class">
          <div>
            <span class="headtitle">1、体积计算</span>
          </div>
          <div style="margin-top: 15px">
            <el-form label-width="155px">
              <el-form-item label="催化剂用量计算值：">
                <span>Zv=</span>
                {{ showData.zv }}
              </el-form-item>
              <el-form-item label="催化剂用量实际值：">
                <span>Ve=</span>
                {{ showData.ve }}
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="border-class">
          <div>
            <span class="headtitle">2、面积计算</span>
          </div>
          <div style="margin-top: 15px">
            <el-form label-width="155px">
              <el-form-item label="建议面速度：">
                <el-input v-model="surfaceSpeed" style="width: 30%"></el-input>
                <el-button
                  type="primary"
                  style="margin-left: 15px"
                  @click="surfaceSpeedSave"
                  >确认</el-button
                >
              </el-form-item>
              <el-form-item label="催化剂截面积计算值：">
                <span>S=</span>
                {{ showData.s }}
              </el-form-item>
              <el-form-item label="反应器尺寸：">
                <el-radio-group v-model="radio" @change="changeRadio">
                  <el-radio value="1" size="large">使用建议尺寸</el-radio>
                  <el-radio value="2" size="large">输入尺寸</el-radio>
                </el-radio-group>
                <el-input
                  v-model="showData.reactorL"
                  style="width: 250px; margin-left: 15px"
                  v-show="radio == '2'"
                >
                  <template #prepend>L:</template>
                  <template #append>mm</template>
                </el-input>
                <el-input
                  v-model="showData.reactorW"
                  style="width: 250px; margin-left: 15px"
                  v-show="radio == '2'"
                >
                  <template #prepend>W:</template>
                  <template #append>mm</template>
                </el-input>

                <el-button
                  type="primary"
                  style="margin-left: 15px"
                  @click="reactorSave"
                  >确认</el-button
                >
              </el-form-item>
              <el-form-item label="催化剂建议阵列：">
                <span>X：</span>
                <span>{{ showData.suggestCatalystsX }}</span>
                <span style="margin-left: 50px">Y：</span>
                <span>{{ showData.suggestCatalystsY }}</span>
              </el-form-item>
              <el-form-item label="催化剂设计阵列：">
                <el-input v-model="showData.matrixX" style="width: 250px">
                  <template #prepend>X:</template>
                </el-input>
                <el-input
                  v-model="showData.matrixY"
                  style="width: 250px; margin-left: 15px"
                >
                  <template #prepend>Y:</template>
                </el-input>
                <el-radio-group v-model="radioCheck" style="margin-left: 15px">
                  <el-radio value="1" size="large">校验</el-radio>
                  <el-radio value="2" size="large">不校验</el-radio>
                </el-radio-group>

                <el-button
                  type="primary"
                  style="margin-left: 15px"
                  @click="matrixSave"
                  >确认</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="border-class">
          <div>
            <span class="headtitle">3、高度计算</span>
          </div>
          <div style="margin-top: 15px">
            <el-form label-width="155px">
              <el-form-item label="建议高度：">
                <span>{{ showData.suggestH }}</span>
              </el-form-item>
              <el-form-item label="选型高度：">
                <el-input v-model="showData.catalystsH" style="width: 30%">
                </el-input>
                <el-button
                  type="primary"
                  style="margin-left: 15px"
                  @click="hightSave"
                  >确认</el-button
                >
              </el-form-item>
              <el-form-item label="">
                <div>
                  <el-table
                    :data="paginatedData"
                    stripe
                    border
                    @selection-change="handleSelectionChange"
                    style="width: 100%"
                  >
                    <el-table-column
                      type="selection"
                      :selectable="selectable"
                      width="55"
                    />
                    <el-table-column prop="moduleName" label="催化剂模块型号" />
                    <el-table-column prop="catalystsH" label="催化剂高度" />
                  </el-table>
                  <el-pagination
                    style="
                      margin-top: 10px;
                      text-align: center;
                      justify-content: center;
                    "
                    @update:current-page="handleCurrentChange"
                    @update:page-size="handleSizeChange"
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 15, 20, 50]"
                    layout="prev, pager,sizes, next,total"
                    :total="total"
                  >
                  </el-pagination>
                </div>
              </el-form-item>

              <el-form-item label="输入催化剂层数：" style="margin-top: 15px">
                <el-input
                  v-model="showData.floors"
                  type="number"
                  style="width: 30%"
                  min="1"
                  step="1"
                >
                  <template #prepend>CS:</template>
                </el-input>
                <el-button
                  type="primary"
                  style="margin-left: 15px"
                  @click="floorsSave"
                  >确认</el-button
                >
              </el-form-item>
              <el-form-item label="催化剂类型："
                >{{ showData.selectModuleName }}
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div style="margin-top: 15px">
          <div style="margin-top: 15px">
            <el-form label-width="155px">
              <el-form-item label="催化剂用量实际值：">
                <span>Vc={{ showData.vc }}</span>
                <span style="margin-left: 200px">（Vc=0.466*0.466*H*N）</span>
              </el-form-item>
              <el-form-item label="实际裕量：">
                <span>Rc={{ showData.rc }}</span>
                <span style="margin-left: 200px"
                  >（Rc=Vc/Zv） （1.0≤R≤1.3）</span
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div style="margin-top: 15px; text-align: center">
          <el-button
            type="primary"
            style="margin-left: 15px"
            @click="makeProject"
            >方案生成</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRoute } from "vue-router";
import { ref, onMounted } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

const route = useRoute();
const id = route.params.id;
const batchId = route.params.batchId;

// 获取状态数据
const router = useRouter(); //页面跳转用

const reactorLQuery = route.query.reactorL ? route.query.reactorL : "";
const reactorWQuery = route.query.reactorW ? route.query.reactorW : "";

const surfaceSpeed = ref("1.8");
const floors = ref("");
const reactorL = ref(""); //反应器长度
const reactorW = ref(""); //反应器宽度
if (reactorLQuery != "") {
  reactorL.value = reactorLQuery;
}
if (reactorWQuery != "") {
  reactorW.value = reactorWQuery;
}

const allComputedList = ref([]); //所有计算列表
const activeName = ref(""); //当前选中的tab
const tabData = ref([]); //tab数据

const showData = ref({}); //展示的数据

const radio = ref("1"); //反应器尺寸选择

const radioCheck = ref("1"); //校验选择

const tableData = ref([]); //表格数据

const selectTableData = ref([]); //表格勾选数据

const reactorLValue = ref("");
const reactorWValue = ref("");

const currentPage = ref(1);
const pageSize = ref(5);

const categoryName = ref(""); //催化剂类型号

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 总数据量
const total = computed(() => tableData.value.length);

function back() {
  // 接收并解析对象
  const objectData = {};
  if (route.query.objectData) {
    objectData.value = JSON.parse(route.query.objectData);
  }
  router.push({
    path: `/projects/projectData/detail/${id}`,
    query: {
      objectData: JSON.stringify(objectData.value),
    },
  });
}

function handleCurrentChange(val) {
  currentPage.value = val;
}

// 每页条数变化
function handleSizeChange(val) {
  pageSize.value = val;
  currentPage.value = 1;
}

function tabClick(tab, event) {
  activeName.value = tab.props.name;
  getShowData();
}

function changeRadio() {
  if (radio.value == "2") {
    showData.value.reactorL = reactorL.value;
    showData.value.reactorW = reactorW.value;
  } else {
    showData.value.reactorL = "";
    showData.value.reactorW = "";
  }
  getMatrix();
}

//设置流速
function surfaceSpeedSave() {
  if (surfaceSpeed.value == "") {
    ElMessage.error("请输入建议面速度!");
    return;
  }
  request({
    url: "/system/project/v2/setFlow",
    method: "put",
    data: {
      flowRate: surfaceSpeed.value,
      schemeComputeId: showData.value.schemeComputeId,
    },
  }).then((response) => {
    if (response.code == 200) {
      getShowData("setFlow");
      // getMatrix();
    }
  });
}

//获取反应器尺寸
function getMatrix() {
  // request({
  //   url: "/system/project/v2/getMatrixSize",
  //   method: "post",
  //   data: { schemeComputeId: showData.value.schemeComputeId },
  // }).then((response) => {
  //   if (response.code == 200) {
  //     showData.value.suggestMatrixX = response.data.suggestMatrixX;
  //     showData.value.suggestMatrixY = response.data.suggestMatrixY;
  //   }
  // });
  if (radio.value == "1") {
    // showData.value.suggestCatalystsX = (
    //   Math.sqrt(showData.value.s) * 1000
    // ).toFixed(2);
    // showData.value.suggestCatalystsY = (
    //   Math.sqrt(showData.value.s) * 1000
    // ).toFixed(2);
    reactorLValue.value = (Math.sqrt(showData.value.s) * 1000).toFixed(0);
    reactorWValue.value = (Math.sqrt(showData.value.s) * 1000).toFixed(0);
  }
}

function reactorSave() {
  if (
    radio.value == "2" &&
    (showData.value.reactorL == "" || showData.value.reactorW == "")
  ) {
    ElMessage.error("请先填写反应器尺寸!");
    return;
  }
  reactorLValue.value =
    radio.value == "2" ? showData.value.reactorL : reactorLValue.value;
  reactorWValue.value =
    radio.value == "2" ? showData.value.reactorW : reactorWValue.value;
  request({
    url: "/system/project/v2/getMatrixSize",
    method: "post",
    data: {
      reactorL: reactorLValue.value,
      reactorW: reactorWValue.value,
      schemeComputeId: showData.value.schemeComputeId,
    },
  }).then((response) => {
    if (response.code == 200) {
      showData.value.suggestCatalystsX = response.data.suggestMatrixX;
      showData.value.suggestCatalystsY = response.data.suggestMatrixY;
      showData.value.matrixX = Math.trunc(response.data.suggestMatrixX);
      showData.value.matrixY = Math.trunc(response.data.suggestMatrixY);
    }
  });
}

function matrixSave() {
  if (showData.value.matrixX == "" || showData.value.matrixY == "") {
    ElMessage.error("请先填写催化剂阵列尺寸!");
    return;
  }

  if (
    showData.value.suggestCatalystsX === undefined ||
    showData.value.suggestCatalystsY === undefined
  ) {
    ElMessage.error("请先确认反应器尺寸!");
    return;
  }

  request({
    url: "/system/project/v2/getSuggestH",
    method: "put",
    data: {
      matrixX: showData.value.matrixX,
      matrixY: showData.value.matrixY,
      reactorL: parseInt(reactorLValue.value),
      reactorW: parseInt(reactorWValue.value),
      schemeComputeId: showData.value.schemeComputeId,
      needCheck: radioCheck.value == "1" ? true : false,
    },
  }).then((response) => {
    if (response.code == 200) {
      showData.value.suggestH = response.data.suggestH;
      //  getShowData();
    }
  });
  request({
    url: "/system/project/v2/checkArea",
    method: "post",
    data: {
      matrixX: showData.value.matrixX,
      matrixY: showData.value.matrixY,
      schemeComputeId: showData.value.schemeComputeId,
    },
  }).then((response) => {
    if (response.code == 200) {
    }
  });
}

//选型高度点击
function hightSave() {
  tableData.value = [];
  if (showData.value.catalystsH == "") {
    ElMessage.error("请先填写选型高度!");
    return;
  }

  request({
    url: "/system/project/v2/getCatalysts",
    method: "post",
    data: {
      schemeComputeId: showData.value.schemeComputeId,
      catalystsH: showData.value.catalystsH,
    },
  }).then((response) => {
    if (response.data) {
      //如果有的话就展示出来
      tableData.value.push({
        moduleName: response.data.moduleName,
        catalystsH: response.data.catalystsH,
      });
    } else {
      tableData.value = [];
      ElMessage.error(
        "该高度下无对应催化剂模块型号，将展示全部催化剂模块型号!"
      );
      //没有的话就展示全部的催化剂
      request({
        url: "/catalyzer/catalyzerData/list",
        method: "get",
        params: { categoryName: categoryName.value },
      }).then((response) => {
        console.log(response);
        if (response.rows.length > 0) {
          tableData.value = response.rows.map((item) => {
            return {
              moduleName: item.moduleName,
              catalystsH: item.catalystsH,
            };
          });
        }
      });
    }
  });
}

//表格勾选
function handleSelectionChange(val) {
  selectTableData.value = val;
}

function floorsSave() {
  if (showData.value.floors == "") {
    ElMessage.error("请先填写催化剂层数!");
    return;
  }
  if (showData.value.floors == "0") {
    ElMessage.error("请先填写正确的催化剂层数!");
    return;
  }
  if (showData.value.floors == 1 && tableData.value.length == 1) {
    if (tableData.value.length == 1) {
      showData.value.selectModuleName = tableData.value[0].moduleName;
    }
  } 
  // else {
  //   if (showData.value.floors != selectTableData.value.length) {
  //     ElMessage.error("催化剂层数和选择的催化剂数量不匹配!");
  //     return;
  //   }
  // }
  showData.value.selectModuleName = selectTableData.value
    .map((item) => item.moduleName)
    .join(",");
  request({
    url: "/system/project/v2/setFloors",
    method: "put",
    data: {
      schemeComputeId: showData.value.schemeComputeId,
      floors: showData.value.floors,
    },
  }).then((response) => {
    request({
      url: "/system/project/v2/setCatalysts",
      method: "post",
      data: {
        schemeComputeId: showData.value.schemeComputeId,
        moduleName: showData.value.selectModuleName,
      },
    }).then((response) => {
      request({
        url: "/system/project/v2/" + batchId,
        method: "get",
        params: {},
      }).then((response) => {
        if (response.data.computeList.length > 0) {
          const showValue = response.data.computeList.filter(
            (item) => item.conditionType === activeName.value
          )[0];
          showData.value.vc = showValue.vc;
          showData.value.rc = showValue.rc;
        }
      });
    });
  });
}

function makeProject() {
  request({
    url: "/system/project/v2/submit",
    method: "post",
    data: {
      schemeComputeId: showData.value.schemeComputeId,
      conditionType: activeName.value,
    },
  }).then((response) => {
    console.log(response);
    if (response.code == 200) {
      ElMessage.success("成功生成方案");
      router.push(
        `/projects/projectData/designDetailProject/${id}/${batchId}/${showData.value.schemeComputeId}`
      );
    }
  });
}

function getShowData(value) {
  request({
    url: "/system/project/v2/" + batchId,
    method: "get",
    params: {},
  }).then((response) => {
    if (response.data.computeList.length > 0) {
      const beforecatalystsH = showData.value.catalystsH;
      showData.value = response.data.computeList.filter(
        (item) => item.conditionType === activeName.value
      )[0];
      showData.value.catalystsH = beforecatalystsH
        ? showData.value.catalystsH
        : "";
      if (
        value ||
        (showData.value.reactorL != null && showData.value.reactorW != null)
      ) {
        getMatrix();
      }
    }
  });
}

function getList() {
  request({
    url: "/system/project/v2/" + batchId,
    method: "get",
  }).then((response) => {
    categoryName.value = response.data.categoryName;
    if (response.data.computeList.length > 0) {
      allComputedList.value = response.data.computeList;
      for (let i = 0; i < response.data.computeList.length; i++) {
        tabData.value.push({
          conditionType: response.data.computeList[i].conditionType,
          conditionName: response.data.computeList[i].conditionType,
        });
      }
      activeName.value = tabData.value[0].conditionName; //默认选中第一个tab

      getShowData(); //获取展示数
    }
  });
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.headtitle {
  margin-left: 10px;
  font-size: 18px;
}

.app-container {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.body-div {
  height: calc(100% - 20px);
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow-y: auto;
}

.shuxian {
  height: 23px;
  width: 5px;
  background-color: #355af0;
}

.form-title {
  font-size: 14px;
  font-weight: 500;
}

.form-text {
  font-size: 14px;
  font-weight: 400;
}

.border-class {
  border: 1px solid #2461ef;
  padding: 15px;
  margin-bottom: 15px;
}
</style>
